<?php

namespace app\admin\controller\aacase;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\exception\PDOException;

/**
 * 批次信息
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Index模型对象
     * @var \app\admin\model\aacase\Index
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\aacase\Index;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 报价单
     */
    public function plogs()
    {

        $ids = $this->request->param('ids');


        if  ($this->request->isAjax()){

            $id=$this->request->param('id');

            $case= Db::name('aa_case')->where(['id'=>$id])->find();

            $list = Db::name('quotaion_log')->where(['quotation_id'=>$case['q_id']])->select();

            $result = array("total" =>count($list), "rows" => $list );

            return json($result);

        }

        $this->assign('ids', $ids);
        return $this->view->fetch();


    }
    public function files()
    {
        $ids = $this->request->param('ids');

        if  ($this->request->isPost()){

            $id=$ids;

            $files=$this->request->param('files');

            $case=Db::name('aa_case')->alias('a')
                ->join('cmf_quotation b','a.q_id=b.id')
                ->where(['a.id'=>$id])
                ->field('a.*,b.order,b.id as quotation_id')->find();

            $list=Db::name('quotaion_log')->alias('a')
                ->join('cmf_catefrolist b','a.catefrolist_id=b.id')
                ->where(['a.quotation_id'=>$case['quotation_id'],'a.seesyatus'=>1])
                ->field('a.*,b.name')
                ->select();


//            print_r($list);

            // 假设要读取的 Excel 文件路径
            $filePath = './'.$files;


            // 加载 Excel 文件
            $spreadsheet = IOFactory::load($filePath);
            // 获取活动工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 获取工作表的最大行数
            $highestRow = $sheet->getHighestRow();
            // 初始化变量
            $highestColumnWithValues = 'A'; // 假设至少有 A 列有值

            // 遍历每一列，从 A 列开始

            $counta=0;
            for ($col = 'A'; ; $col++) {
                $hasValue = false; // 标记当前列是否有值
                $row = 4;
                for ($row = 4; $row <= 4; $row++) {
                    $cellValue = $sheet->getCell($col . $row)->getValue();
                    if ($cellValue !== null && trim($cellValue) !== '') { // 检查是否有值
                        $hasValue = true;
                        break;
                    }
                }
                if (!$hasValue) {
                    break; // 如果当前列没有值，退出循环
                }

                $counta++;
                $highestColumnWithValues = $col; // 更新有值的最高列
            }

            // 从第 3 行开始获取数据到数组
            $data = [];

            $rowData = [];

            $row = 3;
            //除开通用参数
            for ($col = 12; $col <= $counta; $col++) {
                $cell = $sheet->getCellByColumnAndRow($col, $row);
                $value = $cell->getValue();
                if ($value instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
                    $value = $value->getPlainText();
                }
                $rowData[] = $value;
            }
            $data[] = $rowData;

            $arrays=[];
            foreach ($list as $li) {
                $array=[];

                $array['title']=$li['catefrolist_name'];
                $array['gid']=$li['catefrolist_id'];
                $array['size']=$li['size'];
                $array['status']=0;
                $array['set']='';
                $array['money']=$li['money'];
                $array['type']=$li['type'];
                $array['id']=$li['id'];
                $arrays[]=$array;

            }


//        print_r($highestRow);
//        echo "---------";
            // 输出读取的数据（可根据需求处理数据）

            $rowDatas=[];
            $allmoney=0;
            for ($row = 5; $row <= $highestRow; $row++){
                $rowData = [];
                $rowData=[];
                $more=[];

                for ($col = 1; $col <= $counta; $col++) {
                    $cell = $sheet->getCellByColumnAndRow($col, $row);
                    $value = $cell->getValue();

                    if ($value instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
                        $value = $value->getPlainText();
                    }

                    if ($col<12){
                        $rowData[] = $value;
                    }else{
                        $coun=$col-12;
                        $arrays[$coun]['set']=$value;
                        if  ($value == '是'){
                            $allmoney+=$arrays[$coun]['money'];
                        }

                        $more[]=$arrays[$coun];
                    }

                }

//                print_r($rowData);
//                echo "---------";


                $rowData['more']=$more;

                $rowDatas[]=$rowData;

            }
            //最后的数据；  搭配
//            print_r($rowDatas);
            $a=0;
            foreach ($rowDatas as $aa=>$array) {
                $adddata=[];
                $adddata['caseid']=$id;
                $adddata['title']=$array['0'];
                $adddata['code']=$array[1];
                $adddata['spu']=$array[2];
                $adddata['sku']=$array[3];
                $adddata['title_b']=$array[4];
                $adddata['color1']=$array[5];
                $adddata['color2']=$array[6];
                $adddata['size']=$array[7];
                $adddata['sex']=$array[8];
                $adddata['colorpro']=$array[9];
                $adddata['desc']=$array[10];
                $adddata['more']=serialize($array['more']);
                $adddata['createtime']=time();
                $adddata['updatetime']=time();

                if ($adddata['title']){

                    $dp=1;

                    foreach ($array['more'] as $more){
                        if ($more['set']=='是'){
                            $dp=0;
                        }
                    }


                    $adddata['typetie']=$dp;

                    Db::name('newphoto')->insert($adddata);

                    $a++;
                }

            }

            Db::name('aa_case')->where(['id'=>$id])->setInc('count',$a);
            Db::name('aa_case')->where(['id'=>$id])->update(['plan'=>1]);

            $this->success('ok');
        }

        $this->assign('ids', $ids);
        return $this->view->fetch();


    }

    public function del($ids = null)
    {

        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        Db::name('aa_case')->where('id','in',$ids)->delete();


        Db::name('newphoto')->where('caseid','in',$ids)->delete();


        $this->success(__('ok'));

    }

    public function clearphoto($ids = null)
    {



        Db::name('newphoto')->where('caseid','eq',$ids)->delete();
        Db::name('aa_case')->where('id','in',$ids)->setField('count',0);

        $this->success(__('ok'));

    }

}
